import { Component, OnInit } from '@angular/core';
import { NzModalService, NzMessageService } from 'ng-zorro-antd';
import { HttpService } from '@core/services/http.service';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import * as screenfull from 'screenfull';
import {ActivatedRoute, Router} from "@angular/router";
import swal from "sweetalert2";



@Component({
  selector: 'app-course-management',
  templateUrl: './course-management.component.html'
})


export class CourseManagementComponent implements OnInit {
    validateForm: FormGroup;
    style: any = {
        width: '70%'
    };
    IP_PORT = this.http.IP_PORT;
    searchOptions;
    popTitle;
    loading = false;
    modalVisible2 = false;
    Cname = '';
    courNum = '';
    classNum = '';
    cour_id = '';
    _allChecked = false;
    _indeterminate = false;
    _displayData = [];
    _checkTable = [];
    _checkLength = 0;
    saveState = '';
    searchValue = '';
    ids = [];
    _loading = false;
    data = [];
    selectedMultipleOption;
    showProject = false;
    showClass  = false;
    c_loading = false;
    checkClass = [];
    ProjectName;
    addIds = [];
    tableB;
    tableBPi = 1;
    tableBPs = 10;
    classList = [];
    pro = [];
    routes;
    ngOnInit() {

        this.validateForm = this.fb.group({
            C_name         : [ null, [ Validators.required ] ]
        });
        this.getData();

    }

    getFormControl(name) {
        return this.validateForm.controls[ name ];
    }

    getData() {
        this._loading = true;
        let param = {pi: this.tableBPi, ps: this.tableBPs, key: this.searchValue, deviceType:'pc'};
        this.http.getCourseManagerList(param).subscribe(res => {
            this._loading = false;
            this.data = res.list;
            this.tableB = res.total;
            this._displayData = res.list;
        });
    }
    save() {
        for (let i in this.selectedMultipleOption) {
            let item = this.selectedMultipleOption[i].toString()
            this.addIds.push(item);
        }
        if (this.saveState === 'add') {
            if (this.validateForm.valid) {
                this.loading = true;
                let param = {cla_id: this.addIds, cour_name: this.Cname};
                this.http.addCourseManager(param).subscribe(res => {
                    if (res.code == 0) {
                        this.modalVisible2 = false;
                        this.loading = false;
                        this.createMessage('success', res.msg);
                        this.getData();
                    }else {
                        this.modalVisible2 = false;
                        this.loading = false;
                        this.createMessage('error', res.msg);
                        this.getData();
                    }
                });
            } else {
                this.loading = false;
                this.createMessage('error', '请输入完整内容后再保存！');
            }
        }else {
            if (this.validateForm.valid) {
                let params = {cour_name: this.Cname, cour_id: this.cour_id.toString(), cla_id: this.addIds};
                this.http.updateCourseByCourId(params).subscribe(res => {
                    if (res.code == 0) {
                        this.modalVisible2 = false;
                        this.loading = false;
                        this.createMessage('success', res.msg);
                        this.getData();
                    }else {
                        this.modalVisible2 = false;
                        this.loading = false;
                        this.createMessage('error', res.msg);
                        this.getData();
                    }
                });
            }else {
                this.loading = false;
                this.createMessage('error', '请输入完整内容后再保存！');
            }
        }
    }


    modal (state, data) {
        if (state === 'add') {
            this.addIds = [];
            let param = {pi: 1, ps: 9999};
            this.http.getClassListByUid(param).subscribe(res => {
                this.searchOptions = res.list;
            });
            this.modalVisible2 = true;
            this.selectedMultipleOption = [];
            this.popTitle = '新建课程';
            this.Cname = '';
            this.saveState = 'add';
        }else if (state === 'update') {
            this.modalVisible2 = true;
            this.addIds = [];
            let param = {pi: 1, ps: 9999, cour_id: data.cour_id};
            this.selectedMultipleOption = [];
            this.http.getSelectOfClaListByCourId(param).subscribe(res => {
                this.searchOptions = res.list;
                for (let ser in this.searchOptions) {
                    if (this.searchOptions[ser].ischeck === 1) {
                        this.selectedMultipleOption.push(this.searchOptions[ser].cla_id);
                    }
                }
            });
            this.popTitle = '修改课程';
            this.Cname = data.cour_name;
            this.cour_id = data.cour_id;
            this.saveState = 'update';
        }

    }

    search () {
        this.getData();
    }

    delClassById (data) {
        let param = { cour_id: data.cour_id.toString()};
        this.http.deleteCourById(param).subscribe(res => {
            if (res.code == 0) {
                this.createMessage('success', res.msg);
                this.getData();
                param = null;
            }else {
                this.createMessage('error', res.msg);
                param = null;
            }
        });
    }

    showConfirm = (data) => {
        let that = this;
        this.confirmServ.confirm({
            title  : '您是否确认要删除这项内容',
            okText : '确定',
            cancelText: '取消',
            onOk() {
                that.delClassById (data);
            },
            onCancel() {
            }
        });
    };

    _displayDataChange($event) {
        this._displayData = $event;
        this._refreshStatus();
    }

    _refreshStatus() {
        const allChecked = this._displayData.every(value => value.checked === true);
        const allUnChecked = this._displayData.every(value => !value.checked);
        const checkTable = this._displayData.filter(value => value.checked);
        this._allChecked = allChecked;
        this._indeterminate = (!allChecked) && (!allUnChecked);
        this._checkTable = checkTable;
        this._checkLength = checkTable.length;
    }

    _checkAll(value) {
        if (value) {
            this._displayData.forEach(data => {
                data.checked = true;
            });
        } else {
            this._displayData.forEach(data => {
                data.checked = false;
            });
        }
        this._refreshStatus();
    }

    deleteCourListByCourId () {
        this.ids = [];
        this._checkTable.map(m => {
            this.ids.push(m.cour_id.toString());
        });
        let param = { cour_id: this.ids};
        this.http.deleteCourListByCourId(param).subscribe(res => {
            if (res.code == 0) {
                this.createMessage('success', res.msg);
                this.getData();
                param = null;
            }else {
                this.createMessage('error', res.msg);
                param = null;
            }
        });
    }

    allDelete () {
        let that = this;
        this.confirmServ.confirm({
            title  : '您是否确认要批量删除选中的' + this._checkLength + '项内容？',
            okText : '确定',
            cancelText: '取消',
            onOk: () => {
                that.deleteCourListByCourId();
            },
            onCancel() {
            }
        });
    }

    createMessage = (type, text) => {
        this._message.create(type, `${text}`);
    }

    showProjects(data) {
        this.showProject = true;
        this.ProjectName = data.cour_name;
        this.cour_id = data.cour_id;
        this._loading = true;
        let param = {pi: 1, ps: 9999, cour_id: data.cour_id};
        this.http.getPrivateProjectByUserId(param).subscribe(res => {
            this.pro = res.list;
            this._loading = false;
            for (let i in res.list) {
                if (res.list[i].ischeck == 1) {
                    res.list[i].checked = true;
                } else {
                    res.list[i].checked = false;
                }
            }
        });
    }

    CheckFalse() {
        this.showProject = false;
        this.pro.forEach(item => item.checked = false);
    }

    checkProject() {
        this.showProject = false;
        const check = this.pro.filter(value => value.checked);
        this.checkClass = check;
        let p_ids = [];
        for (let c in check) {
           p_ids.push(check[c].p_id.toString());
        }

        let param = {cour_id: this.cour_id, p_id: p_ids};
        this.http.updatePriProToCourByPId(param).subscribe(res => {
            if (res.code == 0) {
                this.createMessage('success', res.msg);
                this.getData();
            }else {
                this.createMessage('error', res.msg);
            }
        });
    }
    ClassAbout (data) {
            this.showClass = true;
            let param = {cour_id: data.cour_id.toString()};
            this._loading = true;
        this.http.getCourAndClaToPriProByCourId(param).subscribe(res => {
        this.classList = res.list;
        // for(let i = 0; i<res.list.length;i++){
        //     res.list[i].p_type = JSON.parse(res.list[i].p_type);
        // }
        this._loading = false;
    });
    }

    play (data) {
        // this.router.navigate(['preview']);
        // if (screenfull.enabled) {
        //
        //     screenfull.toggle();
        //     screenfull.onchange(v=>{
        //      if(!screenfull.isFullscreen){
        //          this.router.navigate(['educational'],{queryParams:{tab:2}})
        //      }
        //     })
        //
        // }

        let cla_id = data.cla_id;
        let p_id = data.p_id;
        let p_type = JSON.parse(data.p_type).value;
        let cour_id = this._displayData[0].cour_id;
        let token =JSON.parse(localStorage.getItem('_user')).access_token;

        this.confirmServ.confirm({

            title  : '您是否确定演练该项目',
            okText : '确定',
            cancelText: '取消',
            onOk: ()=>{

                this.http.quickEntryProject({cla_id:cla_id ,p_type:p_type ,cour_id:cour_id,day:'1' ,exercisetypes:'0' ,p_id:p_id , deviceType:'pc',token:token}).subscribe(data => {

                 //   console.log(data);
                    //this.router.navigate(['preview'],{queryParams:{ 'data': JSON.stringify(data) }})
                  //  this.router.navigate(['preview']);
                    // if (screenfull.enabled) {
                    //
                    //     screenfull.toggle();
                    //     screenfull.onchange(v=>{
                    //      if(!screenfull.isFullscreen){
                    //          this.router.navigate(['educational'],{queryParams:{tab:2}})
                    //      }
                    //     })
                    //
                    // }


                })


            },
            onCancel() {

            }
        });

    }

    constructor(
        private confirmServ: NzModalService,
        private http: HttpService,
        private _message: NzMessageService,
        private fb: FormBuilder,
        private router:Router
    ) {
    }
}
